package com.vpen.account.demo.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vpen.clib.constant.CConstant;
import com.vpen.clib.result.CODE_MSG;
import com.vpen.clib.result.CResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 韦鹏
 * @desc 未登录处理器
 * @date 2022/7/15 14:44
 **/
@Component
@AllArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class UnLoginAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.debug(request.getRequestURI() + ": 未授权", authException);
        response.setContentType(CConstant.CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        CResult<String> error = CResult.error(CODE_MSG.UNAUTHORIZED);
        error.setData(authException.getMessage());
        out.write(objectMapper.writeValueAsString(error));
        out.flush();
        out.close();
    }
}
